import React, { useState } from 'react'
import RequireAuth from './guard/RequireAuth'
import MainLayout from './layout'
import Login from './views/Login'
import NotFound from './views/NotFound'
import {Routes,Route} from 'react-router-dom'
import {filterRoutes} from './router'
import {useSelector} from 'react-redux'
import { useEffect } from 'react'
import _ from 'lodash'

function App() {
  const {userInfo} = useSelector(({user})=>user)
  const [routeList,setRouteList] = useState([])
  useEffect(()=>{
    if(userInfo){
      let {role} = userInfo
      let routes = _.cloneDeep(filterRoutes())
      _.remove(routes,(item)=>{  //删除路由数据包中，用户无权访问的数据包
        return !item.roles.includes(role)
      })
      setRouteList(routes)
    }
  },[])
  return (
    <div className="App">
      <Routes>
        <Route path="/admin" element={
          <RequireAuth>
            <MainLayout/>
          </RequireAuth>
        }>
          {
            routeList.map(item=>{
              return <Route key={item.path} {...item}></Route>
            })
          }
          <Route path="/admin/*" element={<NotFound/>}></Route>
        </Route>
        <Route path="/login" element={<Login/>}></Route>
        <Route path="*" element={<NotFound/>}></Route>
      </Routes>
    </div>
  )
}

export default App
